/****************************************************************************
 * 2023.9 DESKTOP-C9GBBP5
 ****************************************************************************/

using System;
using System.Linq;
using UnityEngine.UI;
using QFramework;

namespace Survivor
{
    public partial class CoinUpgradePanel : UIElement, IController
    {
        private void Awake()
        {
            InitCoinUpgradeItemPrefab();
            CloseBtn.onClick.AddListener(Hide);
        }

        private void InitCoinUpgradeItemPrefab()
        {
            foreach (var coinUpgradeItem in this.GetSystem<CoinUpgradeSystem>().CoinUpgradeItemList)
            {
                CoinUpgradeItemPrefab.InstantiateWithParent(CoinUpgradeItemRoot)
                    .Self(btn =>
                    {
                        var descTxt = btn.GetComponentInChildren<Text>();
                        var itemCache = coinUpgradeItem;
                        descTxt.text = $"{itemCache.Describe} {itemCache.Price}金币";
                        var btnCache = btn;
                        btnCache.onClick.AddListener(() =>
                        {
                            itemCache.Upgrade();
                            AudioKit.PlaySound("AbilityLevelUp");
                        });

                        Action changeAction = () =>
                        {
                            if (itemCache.ConditionCheck())
                            {
                                btnCache.Show();
                            }
                            else
                            {
                                btnCache.Hide();
                            }
                        };
                        itemCache.OnChange.Register(() => { changeAction.Invoke(); })
                            .UnRegisterWhenGameObjectDestroyed(this);
                        changeAction.Invoke();
                        Global.Coin.RegisterWithInitValue(coin =>
                        {
                            CoinTxt.text = $"金币: {coin}";
                            btnCache.interactable = coin >= itemCache.Price;
                        }).UnRegisterWhenGameObjectDestroyed(btnCache);
                    });
            }
        }

        protected override void OnBeforeDestroy()
        {
        }

        public IArchitecture GetArchitecture()
        {
            return Global.Interface;
        }
    }
}